package chat

import (
	"context"
	"errors"
	"fmt"
	"io"

	"github.com/sashabaranov/go-openai"
)

func NewChat(ctx context.Context, credential Credential) *Chat {
	return &Chat{
		ctx:    ctx,
		client: openai.NewClientWithConfig(NewConfig(credential)),
	}
}
func NewConfig(credential Credential) openai.ClientConfig {
	config := openai.DefaultConfig(credential.SecretKey)
	config.BaseURL = credential.Endpoint

	// config.APIType = openai.APITypeOpenAI
	// config.OrgID = credential.Organization

	config.APIType = openai.APITypeAzure
	config.APIVersion = credential.ApiVersion

	// config.APIType = openai.APITypeAzureAD
	// config.APIType = openai.APITypeCloudflareAzure

	// proxyUrl, err := url.Parse(credential.Proxy)
	// if err != nil {
	// 	panic(err)
	// }
	// transport := &http.Transport{
	// 	Proxy: http.ProxyURL(proxyUrl),
	// }
	// config.HTTPClient = &http.Client{
	// 	Transport: transport,
	// }

	return config
}

type Chat struct {
	ctx    context.Context
	client *openai.Client
}

func (r *Chat) ChatCompletion(req openai.ChatCompletionRequest) (response openai.ChatCompletionResponse, err error) {
	return r.client.CreateChatCompletion(r.ctx, req)
}
func (r *Chat) ChatCompletionStream(req openai.ChatCompletionRequest, f func(openai.ChatCompletionStreamResponse)) {
	stream, err := r.client.CreateChatCompletionStream(r.ctx, req)
	if err != nil {
		fmt.Printf("ChatCompletionStream error: %v\n", err)
		return
	}
	defer func(stream *openai.ChatCompletionStream) {
		_ = stream.Close()
	}(stream)

	for {
		response, err := stream.Recv()
		if err != nil {
			if errors.Is(err, io.EOF) {
				fmt.Println("\nStream finished")
				return
			}

			fmt.Printf("\nStream error: %v\n", err)
			return
		}

		f(response)
	}
}
